# coding:utf-8
from .MysqlPool import pool
from tornado import gen


class Teacher:
    # ----------add----------
    @classmethod
    @gen.coroutine
    def add(cls, t_id, t_name, t_wechat= "") -> bool:
        """
        添加教师信息 返回是否成功
        :param t_id: 职工号
        :param t_name: 姓名
        :param t_wechat:
        :return:
        """
        sql = "select count(t_id) as count from tea_info where t_id=%s"
        cursor = yield pool.execute(sql, (t_id,))
        data = cursor.fetchone()
        if data["count"] != 0:
            return False
        sql = "INSERT INTO tea_info (t_id,t_name,t_wechat) VALUES (%s,%s,%s)"
        cursor = yield pool.execute(sql, (t_id, t_name, t_wechat))
        return cursor.rowcount != 0

    # ----------get----------
    @classmethod
    @gen.coroutine
    def get_count(cls) -> int:
        """"
            返回教师数量
            return 返回教师数量
        """
        cursor = yield pool.execute("select count(t_id) as count from tea_info")
        return cursor.fetchone()['count']

    @classmethod
    @gen.coroutine
    def get_all(cls, page_num, num_in_page=10):
        """
        通过页号获取教师数据
        :param page_num: 页号
        :param num_in_page: 一页数量
        :return:
        """
        page_num = int(page_num) - 1
        sql = "select t_id as tid,t_name as tname from tea_info limit %s,%s"
        cursor = yield pool.execute(sql, (page_num * num_in_page, num_in_page))
        if cursor.rowcount == 0:
            return ()
        else:
            return cursor.fetchall()

    @classmethod
    @gen.coroutine
    def get_by_id(cls, t_id):
        """
        通过ID获得教师对象,返回结果或False
        :param t_id: 职工号
        :return:
        """
        sql = "select t_id as tid,t_name as tname from tea_info where t_id = %s"
        cursor = yield pool.execute(sql, (t_id,))
        if cursor.rowcount == 0:
            return ()
        else:
            return cursor.fetchone()

    @classmethod
    @gen.coroutine
    def get_by_wc(cls, t_openid):
        """
        通过微信授权码获得教师对象 返回结果或者()
        :param t_openid:
        :return:
        """
        sql = "select * from tea_info where t_wechat = %s"
        cursor = yield pool.execute(sql, (t_openid,))
        if cursor.rowcount == 0:
            return False
        else:
            return cursor.fetchone()

    # ----------del----------
    @classmethod
    @gen.coroutine
    def del_by_id(cls, t_id) -> bool:
        """
        删除教师信息by T_ID 返回是否成功
        :param t_id: 职工号
        :return:
        """
        parm = (t_id,)
        sql = "delete from tea_info where t_id = %s"
        cursor = yield pool.execute(sql, parm)
        if cursor.rowcount == 0:
            return False
        else:
            return True
